package bat.iog.hytool.reactor.multiple;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;

class MultiWriteHandler {

    private SelectionKey selectionKey;

    public MultiWriteHandler(SelectionKey selectionKey) {
        this.selectionKey = selectionKey;
    }
    
    public void run() {
        try {
            final SocketChannel sc = (SocketChannel) selectionKey.channel();
            //使用线程池，异步处理写请求
            ThreadPool.getPool().submit(new Runnable() {
                @Override
                public void run() {
                    doWrite(sc);
                }
            });
            //写完后，将通道注册为读
            Selector selector = selectionKey.selector();
            SelectionKey sk = sc.register(selector, SelectionKey.OP_READ);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    private void doWrite(SocketChannel sc) {
        ByteBuffer writeBuffer = ByteBuffer.allocate(1024);
        writeBuffer.put("123456".getBytes());
        writeBuffer.flip();
        try {
            sc.write(writeBuffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        System.out.println("处理写。。。");
    }
}
